package com.xian.test;

import com.sun.tools.attach.*;

import java.io.IOException;
import java.util.List;

/**
 * @program: java-agent-premain
 * @description:
 * @author: liru.xian
 * @create: 2021-09-26 17:27
 **/

public class AgentMain {

    public static void main(String[] args)
            throws IOException, AttachNotSupportedException, AgentLoadException, AgentInitializationException {
        List<VirtualMachineDescriptor> list = VirtualMachine.list();
        for (VirtualMachineDescriptor vmd : list) {
            if (vmd.displayName().endsWith("AccountMain")) {
                VirtualMachine virtualMachine = VirtualMachine.attach(vmd.id());
                //动态多次加载会有内存溢出风险！！！字节码加载到jvm内存元空间。并不会清理，考虑加载一次缓存起来使用。
                virtualMachine.loadAgent("/Users/xianliru/学习文档/java-agent-premain/agent-agentmain/target/agent-agentmain-1.0-SNAPSHOT.jar");
                System.out.println("ok");
                //伪卸载，只是清理了加载路径
                virtualMachine.detach();
            }
        }
    }
}
